package model

import (
	"context"
	"go_final/mxshop_srvs/goods_srv/global"
	"strconv"

	"gorm.io/gorm"
)

type Category struct {
	BaseModel
	Name             string    `gorm:"type:varchar(20);not null" json:"name"`
	Level            int32     `gorm:"type:int;not null;default:1" json:"level"`
	IsTap            bool      `gorm:"default:false;not null" json:"is_tap"`
	ParentCategoryID int32     `json:"parent"`
	ParentCategory   *Category `json:"-"` // 外键是自己的话需要使用指针

	// 使用外键做关联查询
	SubCategories []*Category `gorm:"foreignKey:ParentCategoryID;references:ID" json:"sub_categories"`
}

type Brand struct {
	BaseModel
	Name string `gorm:"type:varchar(20);not null"`
	Logo string `gorm:"type:varchar(20);default:'';not null"`
}

// GoodsCategoryBrand 多对多中间表
type GoodsCategoryBrand struct {
	BaseModel
	CategoryID int32 `gorm:"type:int;index:idx_category_brand,unique"` // 创建联合唯一索引
	Category   Category

	BrandID int32 `gorm:"type:int;index:idx_category_brand,unique"` // 创建联合唯一索引
	Brand   Brand
}

// TableName 自定义表名
func (g *GoodsCategoryBrand) TableName() string {
	return "goodscategorybrand"
}

type Banner struct {
	BaseModel
	Image string `gorm:"type:varchar(200);not null"`
	URL   string `gorm:"type:varchar(200);not null"`
	Index int32  `gorm:"type:int;default:1;not null"`
}

type Good struct {
	BaseModel

	CategoryID int32 `gorm:"type:int;not null"`
	Category   Category
	BrandID    int32 `gorm:"type:int;not null"`
	Brand      Brand

	OnSale   bool `gorm:"default:false;not null"`
	ShipFree bool `gorm:"default:false;not null"`
	IsNew    bool `gorm:"default:false;not null"`
	IsHot    bool `gorm:"default:false;not null"`

	Name            string   `gorm:"type:varchar(50);not null"`
	GoodSn          string   `gorm:"type:varchar(50);not null"`
	ClickNum        int32    `gorm:"type:int;default:0;not null"`
	SoldNum         int32    `gorm:"type:int;default:0;not null"`
	FavNum          int32    `gorm:"type:int;default:0;not null"`
	MarketPrice     float32  `gorm:"not null"`
	ShopPrice       float32  `gorm:"not null"`
	GoodsBrief      string   `gorm:"type:varchar(100);not null"`
	Images          GormList `gorm:"type:varchar(1000);not null"`
	DescImages      GormList `gorm:"type:varchar(1000);not null"`
	GoodsFrontImage string   `gorm:"type:varchar(200);not null"`
}

func (g *Good) AfterCreate(tx *gorm.DB) (err error) {
	// 新增完以后将商品数据添加到elasticsearch中
	_, err = global.EsClient.Index().
		Index("mygoods").
		Id(strconv.Itoa(int(g.ID))).
		BodyJson(EsGoods{
			ID:          g.ID,
			CategoryID:  g.CategoryID,
			BrandID:     g.BrandID,
			OnSale:      g.OnSale,
			ShipFree:    g.ShipFree,
			IsNew:       g.IsNew,
			IsHot:       g.IsHot,
			Name:        g.Name,
			ClickNum:    g.ClickNum,
			SoldNum:     g.SoldNum,
			FavNum:      g.FavNum,
			MarketPrice: g.MarketPrice,
			GoodBrief:   g.GoodsBrief,
			ShopPrice:   g.ShopPrice,
		}).
		Do(context.Background())
	if err != nil {
		// Handle error
		return err
	}
	return nil
}
